<!-- 项目统计 另一个版本 （好多个项目的 TJ 列表） -->
<template>
  <ContainerLayoutV2 ref="containerLayoutRef" class="project-statistics-2">
    <template #tables>
      <div class="statistics-container">
        <div class="form-section">
          <el-form :model="formProject" label-width="auto" :inline="true">
            <el-form-item label="项目名称：">
              <el-select v-model="projectValue" placeholder="请选择项目" style="width: 200px" :max-collapse-tags="1" multiple clearable collapse-tags>
                <template #header>
                  <el-checkbox v-model="checkAllProject" :indeterminate="indeterminateProject" @change="handleCheckAllProject">全部</el-checkbox>
                </template>
                <el-option v-for="item in optProjectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="时段：">
              <el-date-picker v-model="formProject.time" type="daterange" range-separator="-" :clearable="false" start-placeholder="开始时间" end-placeholder="结束时间" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleClickBtnSubmit" :loading="isLoading" :icon="Search">查询</el-button>
              <!-- <el-button type="primary" :icon="Download">下载</el-button> -->
              <ExcelExportButton :headerParams="exportHeaderParams" :headerRowLength="1" size="default" :table-data="exportTableData" :fileName="exportFileName" />
            </el-form-item>
          </el-form>
        </div>
        <div class="statistics-section" ref="refStatisticsSection">
          <el-table ref="dataTable" :data="tableData" :height="tableHeight" :cell-class-name="cellClassName" :span-method="objectSpanMethod" @cell-click="handleTableCellClick" border width="100%" header-cell-class-name="table-header-row" empty-text="没有数据">
            <el-table-column prop="projectName" label="项目" min-width="120" fixed />
            <el-table-column prop="projectCode" label="代码" min-width="120" fixed />
            <el-table-column prop="projectCategory" label="类型" min-width="120" fixed />
            <el-table-column label="生产环节" min-width="120" fixed>
              <template #default="scope">
                {{ scope.row.processName }}
              </template>
            </el-table-column>
            <el-table-column prop="status2" label="整体状态" min-width="90" fixed />
            <el-table-column prop="statusName" label="整体进度" min-width="150" fixed>
              <template #default="scope"> {{ scope.row.statusName }}({{ scope.row.num }}) </template>
            </el-table-column>
            <template v-for="item in tableColumnDate">
              <el-table-column :prop="item.label" width="70" resizable :label-class-name="getLabelClassName(item.isSameWeek)">
                <template #header>
                  <div class="table-header-cell">
                    <div>{{ item.label }}</div>
                  </div>
                </template>
                <template #default="scope">
                  {{ scope.row[item.columnName] }}
                </template>
              </el-table-column>
            </template>
            <el-table-column prop="status1" label="状态" min-width="80" fixed="right" />
            <el-table-column prop="monthPlanRemark" label="单月计划" min-width="200" fixed="right" />
            <el-table-column prop="weekRemark" label="本周进度说明" min-width="200" fixed="right" />
            <el-table-column prop="monthRemark" label="本月进度说明" min-width="200" fixed="right" />
          </el-table>
        </div>
      </div>
    </template>
  </ContainerLayoutV2>
  <DialogProjectTaskPlanDetail ref="dialogProjectTaskPlanRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import ContainerLayoutV2 from '../layout/ContainerLayoutV2.vue'
import * as utils from '../utils'
import { Search } from '@element-plus/icons-vue'
import Api from '../api'
import DialogProjectTaskPlanDetail from '../components/dialog/DialogProjectTaskPlanDetail.vue'
import type { CheckboxValueType } from 'element-plus'
import ExcelExportButton from '../layout/ButtonToolbar/ExcelExportButton.vue'

const isLoading = ref(false)
const dialogProjectTaskPlanRef = ref<InstanceType<typeof DialogProjectTaskPlanDetail>>()
const refStatisticsSection = ref()
const checkAllProject = ref(false)
const indeterminateProject = ref(false)
const projectValue = ref<CheckboxValueType[]>([])
const exportFileName = ref('')
const dataResult = ref()
const formProject = reactive({
  name: null,
  desc: '',
  time: [] as any[],
  leader: '',
})
// const calendarValue = ref(new Date())

const exportTableData = ref<any[]>([])
const exportHeaderParams = ref<any[]>([
  // { title: '序号', value: 'index', width: 54 },
])
const tableHeight = ref(400)
const tableData = ref<any[]>([])
const tableColumnDate = ref<any[]>([])
// 项目列表
const optProjectList = ref<any[]>([])
const weeks = ref()

const getLabelClassName = (isSameWeek: boolean) => {
  return isSameWeek ? 'is-same-week' : ''
}

const cellClassName = ({ row, column }: { row: any; column: any; rowIndex: number; columnIndex: number }) => {
  let className = row[column.property + '|className']
  return className
}

/**
 * 设置表格列日期
 *
 * @returns 无返回值
 */
const setTableColumnDate = () => {
  if (formProject.time === null) return

  // 创建一个日期对象，表示起始日期
  const start = formProject.time[0]

  // 创建一个日期对象，表示当前日期
  const end = formProject.time[1]
  // 调用utils.getWeeksBetweenDates方法，计算起始日期和当前日期之间的周数，并赋值给weeks.value
  weeks.value = utils.getWeeksBetweenDates(start, end)

  // 初始化tableColumnDate.value，并遍历weeks.value数组
  tableColumnDate.value = [
    ...weeks.value.map((e: any) => {
      // 将每周的开始日期格式化为'yyyy-MM-dd'格式
      const start = utils.formatDate(e.start, 'yyyy-MM-dd')
      // console.log('start', start)
      // 将每周的结束日期格式化为'yyyy-MM-dd'格式
      const end = utils.formatDate(e.end, 'yyyy-MM-dd')
      // 将每周的开始日期格式化为'yyyy'格式
      const startYear = utils.formatDate(e.start, 'yyyy')
      // 将每周的结束日期格式化为'yyyy'格式
      const endYear = utils.formatDate(e.end, 'yyyy')
      // 将每周的开始日期格式化为'MM-dd'格式
      const startDay = utils.formatDate(e.start, 'MM-dd')
      // 将每周的结束日期格式化为'MM-dd'格式
      const endDay = utils.formatDate(e.end, 'MM-dd')
      // 判断当前日期是否与开始日期在同一周
      const isSameWeek = utils.isSameWeek(start, Date.now())
      // 返回一个对象，包含是否是同一周、标签、列名、开始日期、结束日期、开始年月日、结束年月日等信息
      return { isSameWeek, label: start, columnName: `${start} - ${end}`, start, end, startDay, endDay, startYear, endYear }
    }),
  ]

  // console.log('tableColumnDate.value:', tableColumnDate.value)
  const newColumns = [
    ...tableColumnDate.value.map((e: any) => {
      console.log('e:', e)
      return { title: e.label, value: e.columnName, width: 10 }
    }),
  ]
  exportHeaderParams.value = [
    { title: '项目', value: 'projectName', width: 10 },
    { title: '代码', value: 'projectCode', width: 20 },
    { title: '类型', value: 'projectCategory', width: 10 },
    { title: '生产环节', value: 'processName', width: 10 },
    { title: '整体状态', value: 'status2', width: 10 },
    { title: '整体进度', value: 'statusName', width: 10 },
    { title: '状态', value: 'status1', width: 10 },
    { title: '单月计划', value: 'monthPlanRemark', width: 10 },
    { title: '本周说明', value: 'weekRemark', width: 10 },
    { title: '本月说明', value: 'monthRemark', width: 10 },
  ]
  exportHeaderParams.value.splice(6, 0, ...newColumns)
  // console.log('newColumns.value:', ...newColumns)
  // console.log('exportHeaderParams.value:', exportHeaderParams.value)
}

/**
 * 将 list2 数组转换为 list3 数组
 *
 * @param list2 需要转换的源数组
 * @returns 转换后的目标数组
 */
const transformList2To3 = (list2: any[]) => {
  const list3: any[] = []

  // 遍历 list2 中的每个项目
  list2.forEach((item) => {
    // 创建基础对象
    const baseObj = {
      date: item.date,
      status1: item.status1,
      processName: item.processName,
      status2: item.status2,
      weekRemark: item.weekRemark,
      monthRemark: item.monthRemark,
      projectName: item.projectName,
      projectCategory: item.projectCategory,
      projectCode: item.projectCode,
      monthPlanRemark: item.monthPlanRemark,
    }
    // 创建计划数量对象
    const planObj: any = { ...baseObj, statusName: '制作计划', num: item.planNum }
    // 创建完成数量对象
    const finishObj: any = { ...baseObj, statusName: '实际进度', num: item.finishNum }

    // 处理 list 数组中的数据
    item.list.forEach((wd: any) => {
      // console.log('wd', wd)

      const weekRange = `${wd.weekStartDate} - ${wd.weekEndDate}`

      // 填充计划数量
      planObj[weekRange] = wd.weekPlanNum
      planObj[wd.weekStartDate + '|id'] = wd.id
      // 填充完成数量
      finishObj[weekRange] = wd.weekFinishNum
      finishObj[wd.weekStartDate + '|id'] = wd.id

      let className = ''
      if (item.status2 == '滞后') {
        className = 'danger'
      } else if (item.status2 == '超前') {
        className = 'success'
      } else {
        className = 'primary'
      }
      if (wd.weekPlanNum != null) {
        planObj[wd.weekStartDate + '|className'] = 'warning'
      }
      if (wd.weekFinishNum != null) {
        finishObj[wd.weekStartDate + '|className'] = className
      }
    })

    // 将两个对象添加到结果数组
    list3.push(planObj, finishObj)
  })

  return list3
}

/**
 * 处理表格单元格点击事件
 *
 * @param row 被点击的行数据
 * @param column 被点击的列数据
 */
const handleTableCellClick = async (row: any, column: any) => {
  // console.log('row', row[column.property + '|id'])
  if (row[column.property + '|id']) {
    const res = await Api.InformationRequirement.getDetailById(row[column.property + '|id'])
    if (res.code == 200) {
      // console.log('res', res.data)
      dialogProjectTaskPlanRef.value?.openDialog(res.data)
    }
  }
}
/**
 * 处理全选项目的逻辑
 *
 * @param val Checkbox 的值
 */
const handleCheckAllProject = (val: CheckboxValueType) => {
  indeterminateProject.value = false
  if (val) {
    projectValue.value = optProjectList.value.map((_) => _.id)
  } else {
    projectValue.value = []
  }
}

/**
 * 获取日期范围内的数据行
 *
 * @returns 返回日期范围内的数据行数组
 */
const getDateRows = async () => {
  // const searchDate = utils.getWeekEnd(new Date())
  const req: any[] = []
  const rows: any[] = []
  projectValue.value.map(async (id) => {
    req.push(
      Api.InformationRequirement.getListAllExport({
        projectId: id,
        weekStartDate: utils.formatDate(formProject.time[0], 'yyyy-MM-dd'),
        weekEndDate: utils.formatDate(formProject.time[1], 'yyyy-MM-dd'),
      })
    )
  })
  const res = await Promise.all(req)
  //   const projectItem = optProjectList.value.find((item) => item.id == id)
  // const { rows } = await rows.forEach((item: any) => {
  //   item.projectName = projectItem.cname
  // })
  res.forEach((e: any) => {
    // const projectItem = optProjectList.value.find((item) => item.id == ids[index])
    // // console.log('projectItem', projectItem.cname)
    // e.rows.map((item: any) => {
    //   item.projectName = projectItem.cname
    // })
    rows.push(...e.rows)
  })
  return rows
}
/**
 * 设置表格数据
 *
 * 从后端API获取项目信息需求列表，并将数据转换为指定格式后设置到表格数据中。
 */
const setTableData = async () => {
  const rows = await getDateRows()
  // console.log('rows', rows)
  // 使用示例
  const list3 = await transformList2To3(rows)
  // const projectItem = optProjectList.value.find((item) => item.id == formProject.name)
  // console.log('list3', list3.length)

  // list3.forEach((item) => {
  //   item.projectName = projectItem.cname
  // })
  dataResult.value = await countByNameAndIndex(list3)
  tableData.value = list3

  // 导出
  exportTableData.value = list3
  exportFileName.value = `项目统计报表-${utils.formatDate(new Date(), 'yyyyMMddHHmmss')}`

  isLoading.value = false
  // console.log('dataResult.value:', dataResult.value)
}
const countByNameAndIndex = (value: any[]) => {
  const nameCountMap: { [key: string]: number } = {}
  const firstIndexMap: { [key: string]: number } = {}
  value.forEach((item: any, index) => {
    if (!nameCountMap[item.projectName]) {
      nameCountMap[item.projectName] = 1
      firstIndexMap[item.projectName] = index
    } else {
      nameCountMap[item.projectName]++
    }
  })

  const mergedObject: { [key: string]: Array<number> } = {}
  for (const name in nameCountMap) {
    mergedObject[firstIndexMap[name]] = [nameCountMap[name], 1]
  }
  // console.log('mergedObject firstIndexMap', firstIndexMap)
  // console.log('mergedObject nameCountMap', nameCountMap)
  // console.log('mergedObject tableData', tableData)
  // console.log('mergedObject B', mergedObject)
  return mergedObject
}
/**
 * 根据行索引和列索引返回表格单元格的合并策略
 *
 * @param param 参数对象，包含行索引和列索引
 * @param param.rowIndex 行索引
 * @param param.columnIndex 列索引
 * @returns 返回单元格的合并策略，包括行合并数和列合并数
 */
const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
  const len = tableColumnDate.value.length + 7
  if (columnIndex <= 2) {
    const res = dataResult.value[rowIndex]
    // console.log('res', res)
    if (res) {
      return res
    } else {
      return [0, 0]
    }
  } else if (columnIndex <= 4 || columnIndex >= len - 1) {
    if (rowIndex % 2 === 0) {
      return [2, 1]
    } else {
      return [0, 0]
    }
  } else {
    return [1, 1]
  }
}

/**
 * 处理项目变化的事件处理函数
 *
 * @param val 传入的项目值，可以是任何类型
 */
const handleClickBtnSubmit = () => {
  isLoading.value = true
  setTableColumnDate()
  setTableData()
}
const setTableHeight = () => {
  tableHeight.value = 0
  nextTick(() => {
    if (refStatisticsSection.value) {
      tableHeight.value = refStatisticsSection.value.offsetHeight
    }
  })
}

/**
 * 获取项目列表
 *
 * @returns 无返回值
 */
const getProjectList = async () => {
  const res = await Api.Projects.getProjectListByParams({
    projectStatus: 1,
    pageSize: 99999,
    display: 0,
  })
  optProjectList.value = res.rows || []
}

onMounted(async () => {
  const currentDate = new Date()
  const year = currentDate.getFullYear()
  const month = currentDate.getMonth()

  // 创建一个日期对象，表示起始日期
  const start = new Date(year, month - 2, 1)
  // 创建一个日期对象，表示当前日期
  const end = new Date(year, month + 3, 0)
  formProject.time = [start, end]
  projectValue.value = []
  getProjectList()
  setTableHeight()
})
</script>

<style lang="scss" scoped>
.is-same-week {
  background-color: aqua;
}
.statistics-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  .date-picker-section {
    position: absolute;
    left: 50%;
    top: 0;
    transform: translateX(-50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .statistics-section {
    // flex: 1;
    transition: all 0.2s ease-in-out;
    flex: 1;
    overflow-x: hidden;
  }

  .statistics-section {
    .left-group,
    .chart-section {
      transition: all 0.2s ease-in-out;
    }
    .left-group {
      // width: 40%;
    }
    .chart-section {
      // width: 60%;
      display: flex;
      align-items: flex-end;
      .chart-item {
        position: relative;
        width: 50%;
        height: 100%;
        .chart-item-title {
          position: absolute;
          top: 210px;
          left: 50%;
          width: auto;
          height: auto;
          line-height: 1;
          z-index: 99999;
          transform: translate(-50%, 0px);
          cursor: default;
          .main-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            text-decoration: none;
            display: block;
          }
          .sub-title {
            font-size: 12px;
            color: #666;
            margin-top: 11px;
          }
        }
      }
    }
    &.view-1-1 {
      .left-group {
        width: 40%;
      }
      .chart-section {
        width: 60%;
      }
    }
    &.view-2-1 {
      .left-group {
        width: 70%;
      }
      .chart-section {
        width: 30%;
      }
    }
    &.view-1-2 {
      .left-group {
        width: 30%;
      }
      .chart-section {
        width: 70%;
      }
    }
  }
  .table-section {
    // flex: 1;
    transition: all 0.2s ease-in-out;
    display: flex;
    flex-direction: column;

    .table-toolbar {
      display: flex;
      justify-self: start;
      flex-wrap: wrap;
      padding-bottom: 10px;
    }
    .table-container {
      flex: 1;
    }
  }
  .form-section {
    display: flex;
    justify-content: flex-start;
  }
  .left-group {
    display: flex;
    flex-direction: column;
  }
  .calendar-section {
    flex: 1;
    position: relative;
    .calendar-container {
      position: absolute;
      left: 0;
      top: 0%;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  }
  &.view-1-1 {
    .statistics-section {
      height: 50%;
    }
    .table-section {
      height: 50%;
    }
  }
  &.view-2-1 {
    .statistics-section {
      height: 67%;
    }
    .table-section {
      height: 33%;
    }
  }
  &.view-1-2 {
    .statistics-section {
      height: 33%;
    }
    .table-section {
      height: 67%;
    }
  }
}
</style>
